<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="考评员姓名" prop="evaluatorName">
        <el-input
          v-model="queryParams.evaluatorName"
          placeholder="请输入考评员姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="考评员编码" prop="evaluatorCode">
        <el-input
          v-model="queryParams.evaluatorCode"
          placeholder="请输入考评员编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="职业名称" prop="professionName">
        <el-input
          v-model="queryParams.professionName"
          placeholder="请输入职业名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="资质等级" prop="qualificationLevel">
        <el-select
          v-model="queryParams.qualificationLevel"
          placeholder="请选择资质等级"
          clearable
          class="!w-240px"
        >
          <el-option label="五级" value="五级" />
          <el-option label="四级" value="四级" />
          <el-option label="三级" value="三级" />
          <el-option label="二级" value="二级" />
          <el-option label="一级" value="一级" />
        </el-select>
      </el-form-item>
      <el-form-item label="资质状态" prop="qualificationStatus">
        <el-select
          v-model="queryParams.qualificationStatus"
          placeholder="请选择资质状态"
          clearable
          class="!w-240px"
        >
          <el-option label="有效" :value="1" />
          <el-option label="无效" :value="0" />
          <el-option label="已过期" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:evaluator:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>

        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:evaluator:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 统计卡片 -->
  <el-row :gutter="20" class="mb-4">
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-blue-600">{{ statistics.totalCount || 0 }}</div>
            <div class="text-gray-500">总考评员数</div>
          </div>
          <Icon icon="ep:user" class="text-4xl text-blue-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-green-600">{{ statistics.validCount || 0 }}</div>
            <div class="text-gray-500">有效资质</div>
          </div>
          <Icon icon="ep:check" class="text-4xl text-green-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-orange-600">{{ statistics.expiringSoonCount || 0 }}</div>
            <div class="text-gray-500">即将过期</div>
          </div>
          <Icon icon="ep:warning" class="text-4xl text-orange-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-red-600">{{ statistics.expiredCount || 0 }}</div>
            <div class="text-gray-500">已过期</div>
          </div>
          <Icon icon="ep:close" class="text-4xl text-red-600" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考评员姓名" align="center" prop="evaluatorName" width="120" />
      <el-table-column label="考评员编码" align="center" prop="evaluatorCode" width="120" />
      <el-table-column label="职业名称" align="center" prop="professionName" width="150" />
      <el-table-column label="资质等级" align="center" prop="qualificationLevel" width="100" />
      <el-table-column label="证书编号" align="center" prop="certificateNumber" width="150" />
      <el-table-column label="颁发日期" align="center" prop="certificateDate" width="120">
        <template #default="scope">
          <span v-if="scope.row.certificateDate">{{ formatDateValue(scope.row.certificateDate) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期至" align="center" prop="validUntil" width="120">
        <template #default="scope">
          <span v-if="scope.row.validUntil">{{ formatDateValue(scope.row.validUntil) }}</span>
          <span v-else class="text-gray-400">长期有效</span>
        </template>
      </el-table-column>
      <el-table-column label="资质状态" align="center" prop="qualificationStatus" width="100">
        <template #default="scope">
          <el-tag :type="getQualificationStatusTagType(scope.row.qualificationStatus)">
            {{ getQualificationStatusText(scope.row.qualificationStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:evaluator:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:evaluator:update']"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="enable" v-if="scope.row.qualificationStatus === 0">
                  启用
                </el-dropdown-item>
                <el-dropdown-item command="disable" v-if="scope.row.qualificationStatus === 1">
                  禁用
                </el-dropdown-item>
                <el-dropdown-item command="renew" v-if="scope.row.qualificationStatus === 2">
                  续期
                </el-dropdown-item>
                <el-dropdown-item command="delete">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <EvaluatorForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <EvaluatorDetail ref="detailRef" />
  

  
  <!-- 续期弹窗 -->
  <EvaluatorRenew ref="renewRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'

// 日期格式化函数 - 与编辑表单保持一致
const formatDateValue = (dateValue: any): string => {
  if (!dateValue) {
    return ''
  }

  // 如果是数组格式 [year, month, day]
  if (Array.isArray(dateValue) && dateValue.length >= 3) {
    const [year, month, day] = dateValue
    return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
  }

  // 如果是字符串且已经是 YYYY-MM-DD 格式，直接返回
  if (typeof dateValue === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(dateValue)) {
    return dateValue
  }

  // 其他格式尝试转换
  if (typeof dateValue === 'string' || typeof dateValue === 'number') {
    const date = new Date(dateValue)
    if (!isNaN(date.getTime())) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }

  return String(dateValue)
}

import {
  EvalEvaluatorQualificationVO, 
  EvalEvaluatorQualificationPageReqVO, 
  getEvaluatorQualificationPage, 
  deleteEvaluatorQualification, 
  exportEvaluatorQualification,
  enableEvaluatorQualification,
  disableEvaluatorQualification,
  getEvaluatorStatistics
} from '@/api/eval/evaluator'
import EvaluatorForm from './EvaluatorForm.vue'
import EvaluatorDetail from './EvaluatorDetail.vue'
import EvaluatorRenew from './EvaluatorRenew.vue'

/** 考评员管理 列表 */
defineOptions({ name: 'EvalEvaluator' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalEvaluatorQualificationVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const statistics = ref<any>({}) // 统计数据
const queryParams = reactive<EvalEvaluatorQualificationPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  evaluatorName: undefined,
  evaluatorCode: undefined,
  professionName: undefined,
  qualificationLevel: undefined,
  qualificationStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getEvaluatorQualificationPage(queryParams)
    list.value = data.list
    total.value = data.total
    
    // 加载统计数据
    await loadStatistics()
  } finally {
    loading.value = false
  }
}

/** 加载统计数据 */
const loadStatistics = async () => {
  try {
    statistics.value = await getEvaluatorStatistics()
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}



/** 续期操作 */
const renewRef = ref()
const openRenew = (id: number) => {
  renewRef.value.open(id)
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalEvaluatorQualificationVO) => {
  switch (command) {
    case 'enable':
      await handleEnable(row.id!)
      break
    case 'disable':
      await handleDisable(row.id!)
      break
    case 'renew':
      openRenew(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 启用考评员 */
const handleEnable = async (id: number) => {
  try {
    await enableEvaluatorQualification(id)
    message.success('启用成功')
    await getList()
  } catch {}
}

/** 禁用考评员 */
const handleDisable = async (id: number) => {
  try {
    await message.confirm('确认禁用该考评员？')
    await disableEvaluatorQualification(id)
    message.success('禁用成功')
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteEvaluatorQualification(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportEvaluatorQualification(queryParams)
    download.excel(data, '考评员资质.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取资质状态标签类型 */
const getQualificationStatusTagType = (status: number) => {
  const typeMap = { 0: 'danger', 1: 'success', 2: 'warning' }
  return typeMap[status] || ''
}

/** 获取资质状态文本 */
const getQualificationStatusText = (status: number) => {
  const textMap = { 0: '无效', 1: '有效', 2: '已过期' }
  return textMap[status] || '未知'
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
